package io.adrainty.bolee.framework.commons.serializer;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonDeserializer;
import io.adrainty.bolee.framework.commons.basic.IEnum;
import io.adrainty.bolee.framework.commons.utils.EnumUtil;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;

/**
 * @author AdRainty
 * @version V1.0.0
 * @since 2025/8/10 下午11:15
 */
public class EnumDeserializer extends JsonDeserializer<IEnum> {

    private final JavaType type;

    public EnumDeserializer(JavaType type) {
        this.type = type;
    }

    @Override
    @SuppressWarnings("unchecked")
    public IEnum deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        // 处理空值情况
        if (p.currentToken() == JsonToken.VALUE_STRING) {
            String value = p.getValueAsString();
            if (StringUtils.isBlank(value)) return null;
        }

        // 正常处理情况
        return EnumUtil.getEnumConstants(p.getValueAsString(), (Class<? extends IEnum>) type.getRawClass());
    }


}
